<template>
  <view class="foundCheck flex flex-column align-center">
    <!-- 头部 -->
    <s-header-title ref="headerTitle" title="家庭记账本" :is-click="false" is-fixed
                  :z-index="10"
                  :background="'#FF7950'" :titleColor="'#FFFFFF'" isDisplayBack showFIcon
                  @getPageHeight="getPageHeight">
    </s-header-title>
    <view :style="{height:`${page.headerHeight}px`}"></view>
    <view class="hW_45"></view>
    <view class="head flex align-center justify-between">
      <view class="left flex align-center justify-between">
        <view class="list flex align-center justify-center"
              v-for="(item,index) in page.billList" :key="index"
              :style="{
                background: item.value == page.billType ? (page.billType == 1 ? '#4CC93B' : '#FF4206') : 'none',
                color: item.value == page.billType ? '#FFFFFF' : `#${index == 1 ? 'FF4206':'4CC93B'}`,
              }"
              :class="item.value != page.billType ? `${page.billType == 1 ? `disburse_border` : `income_border`}` : ''"
              @click.stop="switchingType(index)"
        >
          {{ item.name }}
        </view>
      </view>
      <picker class="right flex align-center" mode="date" @change="timeChange($event)">
        {{ page.select_time }}
        <image class="ml-11" :src="`${IMG_URL}/index/book_found_icon.png`"></image>
      </picker>
    </view>
    <view class="hW_69"></view>
    <view class="amount flex align-end">
      <view class="left" :style="{
          color: page.billType == 1 ? '#4CC93B' : '#FF4206'
        }">
        ￥
      </view>
      <view class="right">
        <input v-model="page.money" :style="{
          color: page.billType == 1 ? '#4CC93B' : '#FF4206'
        }" type="digit" placeholder="收到了多少金额"
               placeholder-class="amount_placeholder" @input="moneyInput($event)"></input>
      </view>
    </view>
    <view class="hW_42"></view>
    <view class="typeList">
      <view v-for="(item,index) in page.list" :key="index">
        <view class="list flex flex-column align-center" v-if="index < 9"
              @click.stop="setImageIndex(index)">
          <image :src="page.select_icon_index == index ? `${nc_image}${item.image_active}` : `${nc_image}${item.image}`"
          ></image>
          <view class="fs_26 fw_500 color_696969 mt_26">{{ item.name }}</view>
        </view>
        <view class="list flex flex-column align-center" @click.stop="getMore" v-if="index == 9">
          <image :src="`${IMG_URL}/index/jiatingjizhangben_more_icon.png`"></image>
          <view class="fs_26 fw_500 color_696969 mt_26">更多</view>
        </view>
      </view>
    </view>
    <view class="hW_69"></view>
    <view class="remark flex flex-column align-center">
      <view class="title wh_702">备注:</view>
      <view class="content mt_16">
        <textarea style="width: 100%"
                  v-model="page.remark"
                  auto-height
                  placeholder="请输入备注"
                  placeholder-class="remark_placeholder"
        />
      </view>
    </view>

    <view class="hW_128"></view>

    <view class="bottomButtonConfig flex align-center justify-center" @click.stop="debounce(addMoments, 1500,true)">
      <image class="mr_10" :src="`${IMG_URL}/index/jiatingjizhangben_icon_confirm.png`"></image>
      保存
    </view>
    <view class="hW_70"></view>
    <view class="bottomButton" v-if="page.options.is_detail == 1" @click.stop="delRecords">
      删除
    </view>

    <uni-popup ref="type_popup" type="bottom">
      <view class="typePopup">
        <view class=" typePupop_head flex justify-between align-center">
          <view class="title ml-44">记账类型</view>
          <image @click="closePopup" class="mr_44" :src="`${IMG_URL}/index/jiatingjizhangben_icon_close.png`"></image>
        </view>
        <view class="hW_28"></view>
        <scroll-view :scroll-y="true" class="typePopup_scroll">
          <view class="flex flex-column align-center">
            <view class="typeList">
              <view class="list flex flex-column align-center" v-for="(item,index) in page.list" :key="index"
                    @click.stop="setImageIndex(index)">
                <image
                  :src="page.select_icon_index == index ? `${nc_image}${item.image_active}` : `${nc_image}${item.image}`"></image>
                <view class="fs_26 fw_500 color_696969 mt_26">{{ item.name }}</view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="hW_28"></view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import HeaderTitle from '@/pages/family/components/headerTitle.vue';
  import { computed, reactive, ref } from 'vue';
  import debounce from '@/sheep/helper/debounce';
  import sheep from '@/sheep';
  import dayjs from 'dayjs';
  import { onLoad } from '@dcloudio/uni-app';

  const _currentTime = new Date().getTime();
  const currentTime = dayjs(new Date().getTime()).format('YYYY年MM月DD日');

  const page = reactive({
    headerHeight: 0,
    select_time: currentTime,
    currentTime: _currentTime,
    // 账单类型 0:支出 1:收入
    billType: 1,
    // 账单列表
    billList: [
      {
        name: '收入',
        value: 1,
      },
      {
        name: '支出',
        value: 2,
      },
    ],
    // 账单金额
    money: '',
    list: [],
    // 当前选择的图片
    select_icon_index: 0,
    // 备注
    remark: '',
    timeShow: false,
    options: {},
    family_book_detail: {},
  });

  const type_popup = ref();

  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const nc_image = computed(() => sheep.$store('AI').nc_image);

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  onLoad(async (options) => {
    page.options = options;
    if (!!page.options.index && page.options.index != -1) {
      page.select_icon_index = page.options.index;
    }
    if (page.options.is_detail == 1) {
      page.family_book_detail = JSON.parse(uni.getStorageSync('family_book_detail'));
      page.money = page.family_book_detail.money;
      page.remark = page.family_book_detail.description;
      page.billType = page.family_book_detail.type;
      page.select_time = !!page.family_book_detail.date ? dayjs(page.family_book_detail.date).format('YYYY年MM月DD日') : dayjs(page.family_book_detail.createtime * 1000).format('YYYY年MM月DD日');
      page.currentTime = new Date(page.family_book_detail.date).getTime();
    }
    await getMoment();
  });

  async function getMoment() {
    let { data } = await sheep.$api.family.getAccountType({ page: 0 });
    let arr = data.sort((a, b) => {
      return b.weigh - a.weigh;
    });
    page.list = arr;
    if (page.options.is_detail == 1) {
      page.list.forEach((item, index) => {
        if (item.id == page.family_book_detail.type_id) {
          page.select_icon_index = index;
        }
      });
    }
  }

  function switchingType(index) {
    page.billType = page.billList[index].value;
  }

  function timeChange(e) {
    page.select_time = dayjs(e.detail.value).format('YYYY年MM月DD日');
    page.currentTime = new Date(e.detail.value).getTime();
  }

  function setImageIndex(index) {
    page.select_icon_index = index;
    type_popup._value.close();
  }

  function getMore() {
    type_popup._value.open();
  }

  async function delRecords() {
    uni.showModal({
      content: '确定删除该条记录？',
      success: async (res) => {
        if (!!res.confirm) {
          let { code, msg } = await sheep.$api.family.delAccount({
            id: page.options.is_detail == 1 ? page.family_book_detail.id : '',
          });
          if (code == 1) {
            sheep.$helper.toast('删除成功');
            uni.removeStorageSync('family_book_detail');
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            sheep.$helper.toast(msg);
          }
        }
      },
    });
  }

  function moneyInput(e) {
    if (!!e.detail.value) {
      let str = e.detail.value.replace(/^\./g, '').replace(/[^\d.]/g, '');
      if (str.indexOf('.') != -1) {
        let arr = str.split('.');
        if (arr[1].length > 2) {
          str = str.substring(0, str.length - 1);
        }
      }
      page.money = str;
    } else {
      page.money = e.detail.value;
    }
  }

  function closePopup() {
    type_popup._value.close();
  }

  async function addMoments() {
    if (Number(page.money) <= 0) {
      sheep.$helper.toast('请输入金额');
      return;
    }
    if (page.options.is_detail != 1) {
      let { msg, code } = await sheep.$api.family.addAccount({
        fab_id: page.options.is_detail == 1 ? page.family_book_detail.id : '',
        family_id: page.options.family_id,
        name: page.list[page.select_icon_index].name,
        type_id: page.list[page.select_icon_index].id,
        description: page.remark,
        money: Number(page.money).toFixed(2),
        type: page.billType,
        date: dayjs(page.currentTime).format('YYYY-MM-DD'),
      });
    } else {
      let { msg, code } = await sheep.$api.family.updateAccount({
        id: page.options.is_detail == 1 ? page.family_book_detail.id : '',
        family_id: page.options.family_id,
        name: page.list[page.select_icon_index].name,
        type_id: page.list[page.select_icon_index].id,
        description: page.remark,
        money: Number(page.money).toFixed(2),
        type: page.billType,
        date: dayjs(page.currentTime).format('YYYY-MM-DD'),
      });
    }
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
</script>


<style scoped lang="scss">
  .foundCheck {
    /* #ifdef H5 */
    margin: auto;
    /* #endif */
    width: 750rpx;
    min-height: 100vh;
    background: #F5F5F5;

    .head {
      width: 702rpx;

      .left {
        width: 364rpx;

        .list {
          width: 178rpx;
          height: 80rpx;
          border-radius: 10rpx 10rpx 10rpx 10rpx;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: bold;
          font-size: 28rpx;
          color: #FF7950;
        }
      }

      .right {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 28rpx;
        color: #FF7950;

        image {
          width: 32rpx;
          height: 28rpx;
        }
      }
    }

    .amount {
      width: 702rpx;

      .left {
        width: 90rpx;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: bold;
        font-size: 80rpx;
        line-height: 65rpx;
        color: #4B4B4B;
      }

      .right {
        width: 642rpx;
        border-bottom: 2rpx solid #CCCCCC;
        padding: 0 9rpx 14rpx 9rpx;

        input {
          height: 50rpx;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: bold;
          font-size: 50rpx;
          color: #4B4B4B;
        }

        .amount_placeholder {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 36rpx;
          color: #C9C9C9;
        }
      }
    }

    .typeList {
      width: 702rpx;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      grid-row-gap: 51rpx;
      grid-column-gap: 30rpx;


      .list {
        white-space: nowrap;

        image {
          width: 80rpx;
          height: 80rpx;
        }
      }
    }

    .remark {
      width: 702rpx;

      .title {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 30rpx;
        color: #4B4B4B;
      }

      .content {
        width: 661rpx;
        min-height: 142rpx;
        background: #FFFFFF;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        border: 2rpx solid #C9C9C9;
        padding: 16rpx 25rpx;
      }

      .remark_placeholder {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 24rpx;
        color: #C9C9C9;
      }
    }

    .bottomButton {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #A0A0A0;
    }

    .bottomButtonConfig {
      width: 362rpx;
      height: 80rpx;
      background: #FF4206;
      border-radius: 50rpx 50rpx 50rpx 50rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: #FFFFFF;

      image {
        width: 29rpx;
        height: 31rpx;
      }
    }

    .typePopup {
      /* #ifdef H5 */
      margin: auto;
      /* #endif */
      width: 750rpx;
      height: 800rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 0rpx 0rpx;

      .typePupop_head {
        width: 750rpx;
        height: 115rpx;
        background: #FFF8E8;
        border-radius: 20rpx 20rpx 0rpx 0rpx;

        .title {
          margin-left: 40rpx;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 500;
          font-size: 48rpx;
          color: #4B4B4B;
        }

        image {
          margin-right: 40rpx;
          width: 32rpx;
          height: 32rpx;
        }
      }

      .typePopup_scroll {
        height: 625rpx;
      }
    }
  }

  .income_border {
    border: 2rpx solid #4CC93B !important;
  }

  .disburse_border {
    border: 2rpx solid #FF4206 !important;
  }
</style>
